using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using System.IO;


namespace SharePointExplorer
{
    /// <summary>
    /// User Control partial class
    /// </summary>
    public partial class Explorator : UserControl
    {

        #region Public Enum

        /// <summary>
        /// View node
        /// </summary>
        public enum View
        {
            /// <summary>
            /// Folder
            /// </summary>
            Folder = 0,
            /// <summary>
            /// File
            /// </summary>
            File
        };

        /// <summary>
        /// Mode for User Control
        /// </summary>
        public enum Mode
        {
            /// <summary>
            /// Save like Window Form
            /// </summary>
            Save = 0,
            /// <summary>
            /// Save for Outlook Module
            /// </summary>
            ZipandEmail
        };

        #endregion

        #region Public Properties

        /// <summary>
        /// Mode view for User control
        /// </summary>
        public Mode ModeView
        {
            get
            {
                return modeView;
            }
            set
            {
                modeView = value;
            }
        }

        /// <summary>
        /// Specified TreeView
        /// </summary>
        public TreeView TGFTreeView
        {
            get
            {
                return treeViewSites;
            }
            set
            {
                treeViewSites = value;
            }
        }

        /// <summary>
        /// SharePoint extracted documents Zip file Path
        /// </summary>
        public string ZipFilePath
        {
            get
            {
                return zipfilepath;
            }
            set 
            {
                zipfilepath = value;
            }
        }
        #endregion

        #region Private Variables

        private Mode modeView = Mode.ZipandEmail;
        private ArrayList listUrl = new ArrayList();
        private string zipfilepath = string.Empty;

        #endregion

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public Explorator()
        {
            InitializeComponent();
        }

        /// <summary>
        /// /Constructor with specified Mode
        /// </summary>
        /// <param name="chosenMode">View Mode</param>
        public Explorator(Mode chosenMode)
            : this()
        {
            modeView = chosenMode;
        }


        #endregion

        /// <summary>
        /// Load the Component
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Explorator_Load(object sender, EventArgs e)
        {

            System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode(Constantes.NOM_RACINE_TVIEW);
            this.treeViewSites.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {treeNode1});

            ListeSharePointSitesReader SharePointListData = new ListeSharePointSitesReader();

            int I = 0;
            TreeNode TempTN = null;
            TreeNode TempSharePointAddressTN = null;
            if (SharePointListData.ServerList.Rows.Count > 0)
            {
                foreach (DataRow Drow in SharePointListData.ServerList.Rows)
                {
                    TempTN = CreateNode(Drow["ServerName"].ToString(), string.Empty, LevelType.Server, Drow["DomainServer"].ToString(), Drow["Login"].ToString(), Drow["Password"].ToString(), string.Empty, DateTime.Now, string.Empty);
                    TempTN.SelectedImageIndex = 9;
                    TempTN.ImageIndex = 9;

                    DataRow[] MesRows = SharePointListData.SharepointSiteList.Select("ListSharePointSites_Id=" + I);
                    foreach (DataRow Marow in MesRows)
                    {
                        TempSharePointAddressTN = CreateNode(Marow["SharePointName"].ToString(), Marow["SharePointURL"].ToString(), LevelType.Web, Drow["DomainServer"].ToString(), Drow["Login"].ToString(), Drow["Password"].ToString(), string.Empty, DateTime.Now, string.Empty);
                        TempSharePointAddressTN.SelectedImageIndex = 2;
                        TempSharePointAddressTN.ImageIndex = 1;
                        TempTN.Nodes.Add(TempSharePointAddressTN);
                    }
                    treeViewSites.Nodes[0].Nodes.Add(TempTN);
                    I++;
                }
            }
            treeViewSites.ExpandAll();
        }

        /// <summary>
        /// when clicking a node, load the subnodes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeViewSites_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string selected = (string)e.Node.Text;

            //propertyGrid.SelectedObject = e.Node.Tag;

            //to avoid loading twice a node
            if (e.Node.Nodes.Count == 0)
            {
                if (((TGFTreeNode)e.Node.Tag).Level == LevelType.Server)
                {
                    // Server case : do nothing
                }
                if (((TGFTreeNode)e.Node.Tag).Level == LevelType.Web)
                {
                    AddSites(((TGFTreeNode)e.Node.Tag).Url, e.Node);
                    AddDocLib(((TGFTreeNode)e.Node.Tag).Url, e.Node);
                }
                else if (((TGFTreeNode)e.Node.Tag).Level == LevelType.DocLib)
                {
                    AddContentDocLib(((TGFTreeNode)e.Node.Parent.Tag).Url, e.Node, selected);
                }
                else if (((TGFTreeNode)e.Node.Tag).Level == LevelType.Folder)
                {
                    AddSubFolderContent(((TGFTreeNode)e.Node.Tag).DocLibUrl, e.Node, ((TGFTreeNode)e.Node.Tag).DocLibName);
                }
                //on file level, change the image index and add in ListURL ArrayList
                else if (((TGFTreeNode)e.Node.Tag).Level == LevelType.File)
                {
                    if (e.Node.StateImageIndex == 6)
                    {
                        e.Node.StateImageIndex = 7;
                        listUrl.Add((TGFTreeNode)e.Node.Tag);
                        BuildListview(listUrl);
                    }
                    else if (e.Node.StateImageIndex == 7)
                    {
                        e.Node.StateImageIndex = 6;
                        listUrl.Remove((TGFTreeNode)e.Node.Tag);
                        BuildListview(listUrl);
                    }
                    else
                    {
                        e.Node.StateImageIndex = 6;
                    }
                }
                else
                {
                    // Default case : do nothing
                }
            }

        }

        /// <summary>
        /// Testing Credentials in XML List Sites File
        /// </summary>
        /// <param name="Domain">Domain User for Credential call</param>
        /// <param name="login">Login User for Credential call</param>
        /// <param name="password">Password User for Credential call</param>
        /// <returns>Credential for SharePoint WebService Call</returns>
        private System.Net.ICredentials GetCredentials(string Domain, string login, string password)
        {
            string DomainWS = string.Empty;
            string LoginWS = string.Empty;
            string PasswordWS = string.Empty;
            System.Net.ICredentials Thecredentials;
            try
            {
                DomainWS = Domain;
                LoginWS = login;
                PasswordWS = password;

                if (LoginWS != null && LoginWS != string.Empty)
                {
                    Thecredentials = new System.Net.NetworkCredential(LoginWS, PasswordWS, DomainWS);
                }
                else
                {
                    Thecredentials = System.Net.CredentialCache.DefaultCredentials;
                }
            }
            catch
            {
                Thecredentials = System.Net.CredentialCache.DefaultCredentials;
            }
            finally
            {
                LoginWS = null;
                PasswordWS = null;
            }
            return Thecredentials;
        }

        /// <summary>
        /// Add sites to a node
        /// </summary>
        /// <param name="url">URL SharePoint Sites</param>
        /// <param name="theNode">Node for add sites</param>
        private void AddSites(string url, TreeNode theNode)
        {
            this.Cursor = Cursors.WaitCursor;

            XmlNode n = null;
            TreeNode newNode = null;
            string suffix = @"/_vti_bin/webs.asmx";
            Webs.WebsSoap w = null;
            try
            {
                w = new SharePointExplorer.Webs.WebsSoap();
                w.PreAuthenticate = true;
                w.Credentials = GetCredentials(((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent);
                w.Url = url + suffix;
                n = w.GetWebCollection();
                foreach (XmlNode sn in n.ChildNodes)
                {
                    newNode = CreateNode(sn.Attributes["Title"].Value, sn.Attributes["Url"].Value, LevelType.Web, ((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent, string.Empty, DateTime.Now, string.Empty);
                    newNode.SelectedImageIndex = 2;
                    newNode.ImageIndex = 1;
                    theNode.Nodes.Add(newNode);
                }
            }
            catch
            {

            }
            finally
            {
                n = null;
                newNode = null;
                w = null;
            }

            theNode.Expand();
            this.Cursor = Cursors.Default;
        }

        /// <summary>
        /// Add Doclib to a Node
        /// </summary>
        /// <param name="url">Doclib URL</param>
        /// <param name="theNode">Node for add DocLib</param>
        private void AddDocLib(string url, TreeNode theNode)
        {
            this.Cursor = Cursors.WaitCursor;

            int serverTemplate = 0;
            string suffix = string.Empty;
            string Nodename = string.Empty;
            string NodeUrl = string.Empty;
            string TempDateModif = string.Empty;
            DateTime DateModified = DateTime.Now;
            Uri TempURIDocLib = null;
            TreeNode newNode = null;
            XmlNode n = null;

            SharePointExplorer.Lists.Lists l = null;

            try
            {
                suffix = @"/_vti_bin/lists.asmx";
                l = new SharePointExplorer.Lists.Lists();
                l.PreAuthenticate = true;
                l.Credentials = GetCredentials(((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent);

                l.Url = url + suffix;

                n = l.GetListCollection();

                foreach (XmlNode sn in n.ChildNodes)
                {
                    //only add documents libraries
                    serverTemplate = Convert.ToInt32(sn.Attributes["ServerTemplate"].Value);
                    if (serverTemplate == 101)
                    {
                        Nodename = sn.Attributes["Title"].Value;
                        NodeUrl = sn.Attributes["DefaultViewUrl"].Value.Replace("/Forms/AllItems.aspx", string.Empty);

                        try
                        {
                            TempDateModif = sn.Attributes["Modified"].Value;
                            DateModified = DateTime.ParseExact(TempDateModif, "yyyyMMdd hh:mm:ss", null);
                        }
                        catch
                        {
                            DateModified = DateTime.Now;
                        }
                        TempURIDocLib = new Uri(((TGFTreeNode)theNode.Tag).Url);
                        NodeUrl = TempURIDocLib.OriginalString.Replace(TempURIDocLib.LocalPath, string.Empty) + NodeUrl;

                        //TODO = Add Athentification 
                        newNode = CreateNode(Nodename, NodeUrl, LevelType.DocLib, ((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent, string.Empty, DateModified, string.Empty);

                        //set the docLibUrl to the Url
                        ((TGFTreeNode)newNode.Tag).DocLibUrl = TempURIDocLib.AbsoluteUri;
                        ((TGFTreeNode)newNode.Tag).DocLibName = Nodename;

                        newNode.SelectedImageIndex = 4;
                        newNode.ImageIndex = 3;

                        theNode.Nodes.Add(newNode);
                    }
                }
            }
            catch
            { }
            finally
            {
                suffix = null;
                Nodename = null;
                NodeUrl = null;
                TempURIDocLib = null;
                newNode = null;
                TempDateModif = null;
                l = null;
                n = null;
            }
            theNode.Expand();

            this.Cursor = Cursors.Default;
        }

        /// <summary>
        /// Add Content Doclib to a Node
        /// </summary>
        /// <param name="url">Doclib URL</param>
        /// <param name="theNode">Node for add content</param>
        /// <param name="listName">DocLib Name</param>
        private void AddContentDocLib(string url, TreeNode theNode, string listName)
        {
            this.Cursor = Cursors.WaitCursor;
            bool addItem = false;
            string suffix = string.Empty;
            string name = string.Empty;
            string URLTempFilename = string.Empty;
            string TypeItem = string.Empty;
            string DocumentAuthor = string.Empty;
            string tempDateModif = string.Empty;
            DateTime DateLastModif = DateTime.Now;
            char[] splitter = null;
            SharePointExplorer.Lists.Lists l = null;
            XmlNode n = null;
            TreeNode newNode = null;
            XmlTextReader xr = null;
            DataSet ds = null;
            LevelType myType;
            try
            {
                suffix = @"/_vti_bin/lists.asmx";
                l = new SharePointExplorer.Lists.Lists();
                l.PreAuthenticate = true;
                l.Credentials = GetCredentials(((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent);
                l.Url = url + suffix;
                n = l.GetListItems(listName, null, null, null, null, null);
                xr = new XmlTextReader(n.OuterXml, XmlNodeType.Element, null);
                ds = new DataSet();
                ds.ReadXml(xr);

                if (ds.Tables["row"] != null)
                {
                    foreach (DataRow sn in ds.Tables["row"].Rows)
                    {
                        name = sn["ows_LinkFilename"].ToString();
                        URLTempFilename = sn["ows_FileRef"].ToString();
                        splitter = new char[] { '#' };
                        URLTempFilename = URLTempFilename.Split(splitter)[1].ToString();
                        splitter = new char[] { '/' };
                        URLTempFilename = url.Split(splitter)[0].ToString() + "//" + url.Split(splitter)[2].ToString() + "/" + URLTempFilename;
                        try
                        {
                            DocumentAuthor = sn["ows_Editor"].ToString();
                            DocumentAuthor = DocumentAuthor.Substring(DocumentAuthor.IndexOf("#") + 1);
                        }
                        catch
                        {
                            DocumentAuthor = string.Empty;
                        }

                        try
                        {
                            tempDateModif = sn["ows_Last Modified"].ToString().Substring(sn["ows_Last Modified"].ToString().IndexOf("#")+1);
                            DateLastModif = DateTime.Parse(tempDateModif);
                        }
                        catch
                        {
                            DateLastModif = DateTime.Now;
                        }

                        //is it a file or a subfolder?
                        TypeItem = string.Empty;
                        try
                        {
                            TypeItem = sn["ows_DocIcon"].ToString();
                        }
                        catch
                        {
                            TypeItem = string.Empty;
                        }

                        if (TypeItem.Length > 0)
                        {
                            myType = LevelType.File;
                        }
                        else
                        {
                            myType = LevelType.Folder;
                        }
                        //filter by Mode: add files , only if we are in 
                        if (this.modeView == Mode.ZipandEmail)
                        {
                            addItem = true;
                        }
                        if (this.modeView == Mode.Save)
                        {
                            if ((myType == LevelType.Folder) || (myType == LevelType.DocLib) || (myType == LevelType.File))
                            {
                                addItem = true;
                            }
                        }
                        if (addItem)
                        {
                            newNode = CreateNode(name, URLTempFilename, myType, ((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent, DocumentAuthor, DateLastModif, TypeItem);
                            theNode.Nodes.Add(newNode);

                            //icons for subfolder
                            if (myType == LevelType.Folder)
                            {
                                newNode.SelectedImageIndex = 4;
                                newNode.ImageIndex = 3;

                                //inherit the parent DocLibUrl from the Parent
                                ((TGFTreeNode)newNode.Tag).DocLibUrl = ((TGFTreeNode)theNode.Tag).DocLibUrl;
                                ((TGFTreeNode)newNode.Tag).DocLibName = ((TGFTreeNode)theNode.Tag).DocLibName;
                            }
                            //icons for file
                            else
                            {
                                newNode.ImageIndex = 8;
                                newNode.SelectedImageIndex = 8;
                                newNode.StateImageIndex = 6;
                            }
                        }
                    }
                }
            }
            catch
            { }
            finally
            {
                suffix = null;
                name = null;
                URLTempFilename = null;
                TypeItem = null;
                DocumentAuthor = null;
                splitter = null;
                tempDateModif = null;
                l = null;
                n = null;
                newNode = null;
                xr = null;
                ds = null;
            }
            theNode.Expand();
            this.Cursor = Cursors.Default;
        }

        /// <summary>
        /// Add SubFloder Content to a node
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="theNode">Node for add content</param>
        /// <param name="docLibName">docLib Name for WebService Call</param>
        private void AddSubFolderContent(string url, TreeNode theNode, string docLibName)
        {
            this.Cursor = Cursors.WaitCursor;

            bool addItem = false;
            LevelType myType;

            char[] splitter = null;
            string suffix = string.Empty;
            string relativePath = string.Empty;
            string TheQuery = string.Empty;
            string name = string.Empty;
            string URLTempFilename = string.Empty;
            string TypeItem = string.Empty;
            string ListeSousRep = string.Empty;
            string DocumentAuthor = string.Empty;
            string tempDateModif = string.Empty;
            DateTime DateLastModif = DateTime.Now;
            SharePointExplorer.Lists.Lists l = null;
            XmlNode n = null;
            XmlNode ndQueryOptions = null;
            TreeNode newNode = null;
            XmlDocument xmlDoc = null;
            XmlTextReader xr = null;
            DataSet ds = null;
            DataTable TableTemp = null;

            try
            {
                suffix = @"/_vti_bin/lists.asmx";

                l = new SharePointExplorer.Lists.Lists();
                l.PreAuthenticate = true;
                l.Credentials = GetCredentials(((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent);

                l.Url = url + suffix;

                xmlDoc = new System.Xml.XmlDocument();

                ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
               
                TheQuery = ((TGFTreeNode)theNode.Tag).Url;
                TheQuery = TheQuery.Replace(((TGFTreeNode)theNode.Tag).DocLibUrl, "");

                if (TheQuery[0].ToString()  == "/")
                {
                    TheQuery = TheQuery.Substring(1);
                }

                ndQueryOptions.InnerXml = "<Folder>" + TheQuery + "</Folder>";
                n = l.GetListItems(docLibName, null, null, null, null, ndQueryOptions);
                xr = new XmlTextReader(n.OuterXml, XmlNodeType.Element, null);

                ds = new DataSet();
                ds.ReadXml(xr);
                TableTemp = ds.Tables["row"];
                if (TableTemp != null)
                {
                    foreach (DataRow sn in ds.Tables["row"].Rows)
                    {
                        name = sn["ows_LinkFilename"].ToString();
                        URLTempFilename = sn["ows_FileRef"].ToString();
                        splitter = new char[] { '#' };
                        URLTempFilename = URLTempFilename.Split(splitter)[1].ToString();
                        splitter = new char[] { '/' };
                        URLTempFilename = url.Split(splitter)[0].ToString() + "//" + url.Split(splitter)[2].ToString() + "/" + URLTempFilename;

                        //is it a file or a subfolder?
                        try
                        {
                            DocumentAuthor = sn["ows_Editor"].ToString();
                            DocumentAuthor = DocumentAuthor.Substring(DocumentAuthor.IndexOf("#") + 1);
                        }
                        catch
                        {
                            DocumentAuthor = string.Empty;
                        }

                        try
                        {
                            tempDateModif = sn["ows_Last Modified"].ToString().Substring(sn["ows_Last Modified"].ToString().IndexOf("#") + 1);

                            DateLastModif = DateTime.Parse(tempDateModif);
                        }
                        catch
                        {
                            DateLastModif = DateTime.Now;
                        }

                        TypeItem = string.Empty;
                        try
                        {
                            TypeItem = sn["ows_DocIcon"].ToString();
                        }
                        catch
                        {
                            TypeItem = string.Empty;
                        }

                        if (TypeItem.Length > 0)
                        {
                            myType = LevelType.File;
                        }
                        else
                        {
                            myType = LevelType.Folder;
                        }

                        if (this.modeView == Mode.ZipandEmail)
                        {
                            addItem = true;
                        }
                        if (this.modeView == Mode.Save)
                        {
                            if ((myType == LevelType.Folder) || (myType == LevelType.DocLib) || (myType == LevelType.File))
                            {
                                addItem = true;
                            }
                        }

                        if (addItem)
                        {
                            newNode = CreateNode(name, URLTempFilename, myType, ((TGFTreeNode)theNode.Tag).DomainIdent, ((TGFTreeNode)theNode.Tag).LoginIdent, ((TGFTreeNode)theNode.Tag).PasswordIdent, DocumentAuthor, DateLastModif, TypeItem);
                            theNode.Nodes.Add(newNode);

                            //icons for subfolder
                            if (myType == LevelType.Folder)
                            {
                                newNode.SelectedImageIndex = 4;
                                newNode.ImageIndex = 3;

                                //inherit the parent DocLibUrl from the Parent
                                ((TGFTreeNode)newNode.Tag).DocLibUrl = ((TGFTreeNode)theNode.Tag).DocLibUrl;
                                ((TGFTreeNode)newNode.Tag).DocLibName = ((TGFTreeNode)theNode.Tag).DocLibName;
                            }
                            //icons for file
                            else
                            {
                                newNode.ImageIndex = 8;
                                newNode.SelectedImageIndex = 8;
                                newNode.StateImageIndex = 6;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                suffix = null;
                splitter = null;
                relativePath = null;
                TypeItem = null;
                ListeSousRep = null;
                name = null;
                URLTempFilename = null;
                DocumentAuthor = null;
                tempDateModif = null;
                l = null;
                n = null;
                newNode = null;
                xr = null;
                ds = null;
                TableTemp = null;
                xmlDoc = null;
                ndQueryOptions = null;
            }
            theNode.Expand();
            this.Cursor = Cursors.Default;
        }

        /// <summary>
        /// Create a node, with the Tag as TGFTreeNode 
        /// </summary>
        /// <param name="title">the title to display</param>
        /// <param name="url">the url to point to</param>
        /// <param name="nodeType">Element Type</param>
        /// <param name="domain">Domain User for Credential</param>
        /// <param name="login">Login User for Credential</param>
        /// <param name="password">Password User for Credential</param>
        /// <param name="Author">SharePoint Author Document</param>
        /// <param name="Lastmodification">Last Modification date for SharePoint Document</param>
        /// <param name="DocumentType">Document Type</param>
        /// <returns>Return the TreeNode to be added</returns>
        public TreeNode CreateNode(string title, string url, LevelType nodeType, string domain, string login, string password, string Author, DateTime Lastmodification, string DocumentType)
        {
            TreeNode newNode = new TreeNode(title);

            TGFTreeNode newTGFNode = new TGFTreeNode();
            newTGFNode.Title = title;
            newTGFNode.Url = url;
            newTGFNode.Level = nodeType;
            newTGFNode.DomainIdent = domain;
            newTGFNode.LoginIdent = login;
            newTGFNode.PasswordIdent = password;
            newTGFNode.AuthorDocument = Author;
            newTGFNode.Lastmodification = Lastmodification;
            newTGFNode.DocumentType = DocumentType;
            newNode.Tag = newTGFNode;

            return newNode;
        }

        /// <summary>
        /// Download Selected files in Random My Documents Sub Folder and zip all
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (this.ModeView == Mode.Save)
            {
                #region Old Code
                ////Save case for list document
                //if (this.TGFTreeView.SelectedNode != null)
                //{
                //    TGFTreeNode currentNode = this.TGFTreeView.SelectedNode.Tag as TGFTreeNode;
                //    if (currentNode != null)
                //    {
                //        if ((currentNode.Level == LevelType.DocLib) || (currentNode.Level == LevelType.Folder))
                //        {
                //            listUrl.Add(((TGFTreeNode)this.TGFTreeView.SelectedNode.Tag).Url);
                //        }
                //        else
                //        {
                //            MessageBox.Show("Please select a document library or a folder to save to", "SharePoint Selection");
                //        }
                //    }
                //}
                //else
                //{
                //    MessageBox.Show("Please select a location to save to", "SharePoint Selection");
                //}
                #endregion
                string TempZipFilePath = string.Empty;
                ExtractAndZipSharePointFiles(ref listUrl);
                if (this.saveZIPFileDialog.ShowDialog() == DialogResult.OK)
                {
                    TempZipFilePath = this.saveZIPFileDialog.FileName;
                    File.Move(this.ZipFilePath, TempZipFilePath);
                    MessageBox.Show("File Extract in : " + TempZipFilePath, "SharePoint Selection");
                }
            }
            else
            {
                ExtractAndZipSharePointFiles(ref listUrl);
            }
        }

        /// <summary>
        /// Extract all selected documents from SharePoint Sites to Zipped file
        /// </summary>
        /// <param name="SharePointDocumentsList"></param>
        private void ExtractAndZipSharePointFiles(ref ArrayList SharePointDocumentsList)
        {
            if (SharePointDocumentsList.Count > 0)
            {
                string SavePath = string.Empty;
                string TempZipFilePath = string.Empty;

                try
                {
                    CleanTempFolders();
                    SavePath = GenerateRandomDirectory();
                    TempZipFilePath = GenerateRandomDirectory() + @"\SharePointFiles.zip";
                    //loop all Array Tiems in listURL ArrayList
                    foreach (TGFTreeNode node in SharePointDocumentsList)
                    {
                        // Save All files in the same folder
                        GetFilefromSharePointURL(node, SavePath);
                    }
                    ZIPLib.ZipFolder(SavePath, TempZipFilePath);

                    this.ZipFilePath = TempZipFilePath;
                }
                catch
                {
                    MessageBox.Show("Error in files extraction", "Error");
                }
                finally
                {
                    SavePath = null;
                    TempZipFilePath = null;
                }
            }
            else
            {
                MessageBox.Show("Please select file from SharePoint", "SharePoint Selection");
            }
        }

        /// <summary>
        /// Create Random Directory in My Documents Folder
        /// </summary>
        /// <returns>Directory path</returns>
        private string GenerateRandomDirectory()
        {
            string SaveTempPath = string.Empty;
            string MyDocumentFolder = string.Empty;
            try
            {
                MyDocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                SaveTempPath = MyDocumentFolder + @"\_SharePoint_Extraction_" + RandomPassword.Generate(8);
                if (Directory.Exists(SaveTempPath))
                {
                    SaveTempPath = GenerateRandomDirectory();
                }
                else
                {
                    Directory.CreateDirectory(SaveTempPath);
                }
            }
            catch
            {
                SaveTempPath = string.Empty;
            }
            finally
            {
                MyDocumentFolder = null;
            }
            return SaveTempPath;
        }

        /// <summary>
        /// Get SharePoint File in the file directory specified
        /// </summary>
        /// <param name="node">Treeview Node</param>
        /// <param name="PathDirectory">Directory to save</param>
        private void GetFilefromSharePointURL(TGFTreeNode node, string PathDirectory)
        {
            int ArraySize = new int();
            string FileDocumentURL = string.Empty;
            byte[] FileData = null;
            //FileStream fs1 = null;
            string PathFile = string.Empty;
            System.Net.WebClient client;
            try
            {
                PathFile = PathDirectory + @"\" + node.Title;
                FileDocumentURL = node.Url;
                client = new System.Net.WebClient();
                client.Credentials = GetCredentials(node.DomainIdent, node.LoginIdent, node.PasswordIdent);
                FileData = client.DownloadData(FileDocumentURL);
                ArraySize = FileData.GetUpperBound(0);

                using (FileStream fs1 = new FileStream(PathFile, FileMode.Create, FileAccess.Write))
                {
                    fs1.Write(FileData, 0, ArraySize);
                    fs1.Close();
                    fs1.Dispose();
                    client.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.ToString());
            }
            finally
            {
                FileDocumentURL = null;
                FileData = null;
                //fs1 = null;
                PathFile = null;
                client = null;
            }


        }

        /// <summary>
        /// Clean Temporary Folder
        /// </summary>
        /// <param name="folderPath">Folder path</param>
        private void CleanTempFolder(string folderPath)
        {
            DirectoryInfo di = new DirectoryInfo(folderPath);
            try
            {
                foreach (FileInfo Fi in di.GetFiles())
                {
                    File.Delete(Fi.FullName);
                }
                Directory.Delete(folderPath, true);
            }
            catch
            { }
            finally
            {
                di = null;
            }

        }

        /// <summary>
        /// Clean Temporary My Documents Sub Folder 
        /// </summary>
        private void CleanTempFolders()
        {
            string MyDocumentFolder = string.Empty;
            string TempPath = string.Empty;
            try
            {
                MyDocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                TempPath =  @"_SharePoint_Extraction_*";
                DirectoryInfo di = new DirectoryInfo(MyDocumentFolder);
                foreach (DirectoryInfo SubFold in di.GetDirectories(TempPath))
                {
                    SubFold.Delete(true);
                }
                //Directory.Delete(folderPath, true);
            }
            catch
            { }
            finally
            {
                MyDocumentFolder = null;
                TempPath = null;
            }

        }

        /// <summary>
        /// Action on Cancel button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btncancel_Click(object sender, EventArgs e)
        {
            if (this.ModeView == Mode.Save)
            {
                Application.Exit();
            }
        }

        /// <summary>
        /// Building listurl ArrayList in ListView
        /// </summary>
        /// <param name="ThelistUrl">ArrayList</param>
        private void BuildListview(ArrayList ThelistUrl)
        {
            TheFileListItem TempFileItem;
            try
            {
                listViewSelectedFiles.Items.Clear();
                foreach(TGFTreeNode TheNode in ThelistUrl)
                {
                    TempFileItem = new TheFileListItem();
                    TempFileItem.FileIconType = TheNode.DocumentType;
                    TempFileItem.FileAuthor = TheNode.AuthorDocument;
                    TempFileItem.FileName = TheNode.Title;
                    TempFileItem.LastModifDate = TheNode.Lastmodification;
                    AddItem(TempFileItem);
                }
            }
            catch
            { }
            finally
            {
                TempFileItem = null;
            }

        }

        /// <summary>
        /// Add an Item in ListView
        /// </summary>
        /// <param name="FileItem">File Item</param>
        private void AddItem(TheFileListItem FileItem)
        {
            int IndexImage = 0;
            string TempIconFile = string.Empty;
            try
            {
                TempIconFile = FileItem.FileIconType.ToString().ToLower() + "icon.gif";
                if (imageIconsList.Images.ContainsKey(TempIconFile))
                {
                    IndexImage = imageIconsList.Images.IndexOfKey(TempIconFile);
                }
                else
                {
                    IndexImage = 0;
                }
            }
            catch
            {
                IndexImage = 0;
            }
            ListViewItem lItem = new ListViewItem(FileItem.FileName.ToString());
            lItem.SubItems.Add(FileItem.FileAuthor.ToString());
            lItem.SubItems.Add(FileItem.FileIconType.ToString());
            lItem.SubItems.Add(FileItem.LastModifDate.ToShortDateString());
            lItem.ImageIndex = IndexImage;
            listViewSelectedFiles.Items.Add(lItem);
        }

    }
}
